package com.yzpass.api.common.config;

import com.yzpass.api.common.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.stream.Collectors;

@ControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {

    // 处理自定义异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return Result.warn(message);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result<Object> handleConstraintViolationException(ConstraintViolationException ex) {
        String message =  ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(","));
        return Result.warn(message);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Object> handle(Exception ex) {
        ex.printStackTrace();
        return Result.error(ex);
    }
}

